package pay

import (
	"awesomeProject/order-web/global"
	"awesomeProject/order-web/proto"
	"context"
	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
	"net/http"
)

func Notify(ctx *gin.Context) {

	appid := global.ServerConfig.AlipayInfo.AppID
	appPrivateKey := global.ServerConfig.AlipayInfo.AppPrivateKey
	alipayPublicKey := global.ServerConfig.AlipayInfo.AliPayPublicKey

	client, err := alipay.New(appid, appPrivateKey, false) // false表示测试环境
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		zap.S().Info("创建支付宝支付客户端失败")
		return
	}
	err = client.LoadAliPayPublicKey(alipayPublicKey)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		zap.S().Info("加载支付宝公钥失败")
		return
	}

	notify, err := client.GetTradeNotification(ctx.Request)
	if err != nil {
		zap.S().Info("获取通知对象失败")
		ctx.JSON(http.StatusInternalServerError, gin.H{})
		return
	}

	_, err = global.OrderSrvClient.UpdateOrderStatus(context.Background(), &proto.OrderStatus{
		OrderSn: notify.OutTradeNo,
		Status:  string(notify.TradeStatus),
	})
	if err != nil {
		zap.S().Info("更新状态失败")
		ctx.JSON(http.StatusInternalServerError, gin.H{})
		return
	}

	// 给支付宝发起通知，表示已完成
	ctx.String(http.StatusOK, "success")

}
